package org.smartboot.sosa.core.module.keygenerator;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 日期格式的自定义主键
 * @author Seer
 * @version DateTimeKeyGenerator.java, v 0.1 2016年1月27日 下午6:10:42 Seer Exp. 
 */
public class DateTimeKeyGenerator implements KeyGenerator{
	private AtomicInteger index = new AtomicInteger();
	/** 节点标识 */
	private String nodeRandom = new DecimalFormat("00").format(new Random().nextInt(99));// 节点固定随机数,降低集群环境冲突几率
	private ThreadLocal<DecimalFormat> decimalFormat = new ThreadLocal<DecimalFormat>() {

		/*
		 * (non-Javadoc)
		 * 
		 * @see java.lang.ThreadLocal#initialValue()
		 */
		@Override
		protected DecimalFormat initialValue() {
			return new DecimalFormat("0000");
		}

	};

	private ThreadLocal<SimpleDateFormat> dateFormat = new ThreadLocal<SimpleDateFormat>() {

		/*
		 * (non-Javadoc)
		 * 
		 * @see java.lang.ThreadLocal#initialValue()
		 */
		@Override
		protected SimpleDateFormat initialValue() {
			return new SimpleDateFormat("yyMMddHHmmss");
		}

	};

	@SuppressWarnings("unchecked")
	public String generator() {
		if (index.get() == 9999) {
			index.set(0);
		}
		String mainPart = dateFormat.get().format(new Date());
		StringBuffer sb = new StringBuffer();
		sb.append(mainPart);
		sb.append(nodeRandom);
		sb.append(decimalFormat.get().format(index.incrementAndGet()));
		return sb.toString();
	}
	static int num=10000000;
	public static void main(String[] args) {
		final DateTimeKeyGenerator generator = new DateTimeKeyGenerator();
		
		for (int i = 0; i < 5; i++) {
			new Thread() {

				/*
				 * (non-Javadoc)
				 * 
				 * @see java.lang.Thread#run()
				 */
				@Override
				public void run() {
//					int i = 1000000;
					long start = System.currentTimeMillis();
					while (num-- > 0) {
//						System.out.println(generator.generator());
						generator.generator();
					}
					System.out.println(System.currentTimeMillis() - start);
				}

			}.start();
		}
	}
}
